import json
import time
import base64
import getpass
import socket
import traceback
import paramiko
#import subprocess
#import shlex

def get_dict_config(config_path) :
  f = open(config_path, 'r')
  d = json.load(f)
  f.close()
  return d

def get_dict_check_server(list_ppserver_address) :
  return dict((server, True) for server in list_ppserver_address)

def launch_ppserver(config, time_delay=500) :
  check = get_dict_check_server(config['list_server_port'])
  ppservers = check.keys()
  cmd_template = config['launch_ppserver_cmd_template']
  ssh_username = config['ssh_username']
  ssh_password = config['ssh_password']
  for server_info in ppservers : 
    server,port = server_info.split(':')
    cmd = cmd_template%(port, time_delay)
    try :
      ssh = paramiko.SSHClient()
      ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      ssh.connect(hostname=server, username=ssh_username, password=ssh_password)
      stdin, stdout, stderr = ssh.exec_command(cmd)
      ssh.close()
    except :
      del check[server_info]
  return check

def go(config, time_delay=500) :
  servers_ok = launch_ppserver(config, time_delay)
  return tuple(servers_ok)

if __name__ == '__main__' :
#  path_config = './config.json'
#  config     = get_dict_config(path_config)
#  if len(config['list_server_port']) > 0 :
#    nb_cpu = 0
#    servers_ok = go(config, 500)
#  else :
#    nb_cpu = 0
#    servers_ok = ('*',) 
  path_config = './config.json'
  config      = get_dict_config(path_config)
  nb_cpu      = 1
  servers_ok  = go(config, 500)

#  time.sleep(3)
  import ppython
  run_pp = ppython.RunningMethod_pp('', nb_cpu, servers_ok)
  for i in xrange(100) :
    run_pp.addCommand('/home/personnels/brixtel/SVN/parpyn/externalProgram.py %s'%(i))
  r = run_pp.run()
  print r

#cmd_ssh = 'ssh -f adelaide "python /home/personnels/brixtel/SVN/parpyn/archives/pp-1.6.4/ppserver.py -p 35000 -t 50"'
